package com.aispeech.imgany.ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.icu.util.IslamicCalendar;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.aispeech.imgany.R;
import com.aispeech.imgany.utils.DipPixelUtil;


public class SelfDurationToast {

    private final static String TAG = "SelfDurationToast";

    public static final int SHOWNAME = 1;
    public static final int OVERTIME = 2;
    public static final int EMPTY = 3;
    private static final int API_LEVEL_19 = 19;
    public static ImageView realLoading;
    public static TextView mTextOne;
    //    public static TextView mTextTwo;
    public static String wifiName;
    private static Context mContext;
    private static View contentView, loadingView;
    //    private static ImageView mArrow;
    private static View mIconView;
    private static boolean isToastAlive = false;

    private static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d(TAG, "handleMessage: msg.what = " + msg.what);
            switch (msg.what) {
                case SHOWNAME:
                    isToastAlive = true;
                    showAnimation();
                    setTextColor("识别成功，请说查看详情");
                    mHandler.postDelayed(mHide, 6000);
                    break;
                case OVERTIME:
                    showAnimation();
                    mTextOne.setText("请求超时，请稍后再试！");
                    mHandler.postDelayed(mHide, 4500);
                    break;
                case EMPTY:
                    showAnimation();
                    mTextOne.setText("无数据返回！");
                    mHandler.postDelayed(mHide, 4500);
                    break;
            }
        }
    };

    private static void setTextColor(String text) {
        mTextOne.setText(setColorText(text, Color.rgb(17, 150, 238), 7, 11));
    }

    public static boolean isIsToastAlive() {
        return mView != null && isToastAlive;
    }

    static SpannableStringBuilder setColorText(@NonNull String text, @NonNull int color, int start, int end) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(text);
        ForegroundColorSpan span = new ForegroundColorSpan(color);
        builder.setSpan(span, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return builder;
    }

    private static void showAnimation() {
        circleMissingAnimation();
        mIconView.setVisibility(View.VISIBLE);
        contentView.setVisibility(View.VISIBLE);

        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.anim_left_to_right);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                showResult();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        contentView.startAnimation(animation);

    }

    private static void circleMissingAnimation() {
        realLoading.clearAnimation();
        loadingView.setVisibility(View.GONE);
    }

    private static void showResult() {
        ObjectAnimator animX = ObjectAnimator.ofFloat(mIconView,
                "scaleX", 1f, 0.9f);
        ObjectAnimator animY = ObjectAnimator.ofFloat(mIconView,
                "scaleY", 1f, 0.9f);
        ObjectAnimator animAlpha2 = ObjectAnimator.ofFloat(mTextOne,
                "alpha", 0f, 1f);
        AnimatorSet set = new AnimatorSet();
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                mIconView.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
                mTextOne.setVisibility(View.VISIBLE);
            }
        });
        set.setDuration(250);
        set.play(animAlpha2).with(animX);
        set.play(animX).with(animY);
        set.start();
    }

    public static SelfDurationToast makeText(final Context context, String text, int timeoutDuration, int type) {
        SelfDurationToast result = new SelfDurationToast(context);

        mContext = context;
        wifiName = text;
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.wifi_change_toast, null);
        view.setBackgroundResource(R.color.transparent);

        realLoading = (ImageView) view.findViewById(R.id.loding_iv);
        realLoading.setImageResource(R.drawable.real_loading);
        Animation loadingAnimation = AnimationUtils.
                loadAnimation(context, R.anim.loading_animation);
        realLoading.setAnimation(loadingAnimation);

        mIconView = view.findViewById(R.id.wifi_result_icon);
        contentView = view.findViewById(R.id.wifi_result_content);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        loadingView = view.findViewById(R.id.loading_content);
        mTextOne = (TextView) view.findViewById(R.id.tv_clean_rocket);
        result.mNextView = view;
        result.mDuration = timeoutDuration;
        return result;
    }

    private final static long PRETENT_LOADING_TIME = 1500;

    private static void readyShow(final int wifiState) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = SHOWNAME;
                msg.obj = wifiState;
                handler.sendMessageDelayed(msg, PRETENT_LOADING_TIME);
            }
        }).start();
    }

    public static void nothingCallBack() {
        if (mView != null) {
            handlerOver();
        }
    }

    public static void loadDoneAndShow() {
        if (mView != null) {
            mHandler.removeCallbacks(mOverTime);
            Message msg = new Message();
            msg.what = SHOWNAME;
            msg.obj = 1;
            handler.sendMessage(msg);
        }
    }


    public static final int LENGTH_SHORT = 2000;
    public static final int LENGTH_LONG = 3500;

    private static final Handler mHandler = new Handler();
    private static int mDuration = LENGTH_SHORT;
    private int mGravity = Gravity.CENTER;
    private int mX, mY;
    private float mHorizontalMargin;
    private float mVerticalMargin;
    private static View mView;
    private View mNextView;

    private static WindowManager mWM;
    private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();


    public SelfDurationToast(Context context) {
        init(context);
    }

    /**
     * Set the view to show.
     *
     * @see #getView
     */
    public void setView(View view) {
        mNextView = view;
    }

    /**
     * Return the view.
     *
     * @see #setView
     */
    public View getView() {
        return mNextView;
    }

    /**
     * Set how long to show the view for.
     *
     * @see #LENGTH_SHORT
     * @see #LENGTH_LONG
     */
    public void setDuration(int duration) {
        mDuration = duration;
    }

    /**
     * Return the duration.
     *
     * @see #setDuration
     */
    public int getDuration() {
        return mDuration;
    }

    /**
     * Set the margins of the view.
     *
     * @param horizontalMargin The horizontal margin, in percentage of the
     *                         container width, between the container's edges and the
     *                         notification
     * @param verticalMargin   The vertical margin, in percentage of the
     *                         container height, between the container's edges and the
     *                         notification
     */
    public void setMargin(float horizontalMargin, float verticalMargin) {
        mHorizontalMargin = horizontalMargin;
        mVerticalMargin = verticalMargin;
    }

    /**
     * Return the horizontal margin.
     */
    public float getHorizontalMargin() {
        return mHorizontalMargin;
    }

    /**
     * Return the vertical margin.
     */
    public float getVerticalMargin() {
        return mVerticalMargin;
    }

    /**
     * Set the location at which the notification should appear on the screen.
     *
     * @see Gravity
     * @see #getGravity
     */
    public void setGravity(int gravity, int xOffset, int yOffset) {
        mGravity = gravity;
        mX = xOffset;
        mY = yOffset;
    }

    /**
     * Get the location at which the notification should appear on the screen.
     *
     * @see Gravity
     * @see #getGravity
     */
    public int getGravity() {
        return mGravity;
    }

    /**
     * Return the X offset in pixels to apply to the gravity's location.
     */
    public int getXOffset() {
        return mX;
    }

    /**
     * Return the Y offset in pixels to apply to the gravity's location.
     */
    public int getYOffset() {
        return mY;
    }

    /**
     * schedule handleShow into the right thread
     */
    public void show() {
        setGravity(Gravity.LEFT | Gravity.TOP, DipPixelUtil.dip2px(mContext, 10), DipPixelUtil.dip2px(mContext, 40));
        mHandler.post(mShow);
        if (mDuration > 0) {
            mHandler.postDelayed(mOverTime, mDuration);
        }
    }

    /**
     * schedule handleHide into the right thread
     */
    public void hide() {
        mHandler.post(mHide);
    }

    private final Runnable mShow = new Runnable() {
        public void run() {
            handleShow();
        }
    };

    private static final Runnable mHide = new Runnable() {
        public void run() {
            handleHide();
        }
    };

    private static final Runnable mOverTime = new Runnable() {
        public void run() {
            handlerOver();
        }
    };

    private void init(Context context) {
        final WindowManager.LayoutParams params = mParams;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;

        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;

        params.format = PixelFormat.TRANSLUCENT;
        params.windowAnimations = android.R.style.Animation_Toast;
        int currSDK_INT = Build.VERSION.SDK_INT;
        if (currSDK_INT < API_LEVEL_19) {
            params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_TOAST;
        }

        mWM = (WindowManager) context.getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
    }


    private void handleShow() {

        if (mView != mNextView) {
            // remove the old view if necessary
            handleHide();
            mView = mNextView;
//            mWM = WindowManagerImpl.getDefault();
            final int gravity = mGravity;
            mParams.gravity = gravity;
            if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
                mParams.horizontalWeight = 1.0f;
            }
            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
                mParams.verticalWeight = 1.0f;
            }
            mParams.x = mX;
            mParams.y = mY;
            mParams.verticalMargin = mVerticalMargin;
            mParams.horizontalMargin = mHorizontalMargin;
            if (mView.getParent() != null) {
                mWM.removeView(mView);
            }
            mWM.addView(mView, mParams);
        }
    }

    public static void handlerOver() {
        handler.removeMessages(SHOWNAME);
        handler.removeMessages(EMPTY);
        handler.removeMessages(OVERTIME);
        handler.sendEmptyMessage(OVERTIME);
    }

    public static void handlerEmpty(){
        handler.removeMessages(SHOWNAME);
        handler.removeMessages(OVERTIME);
        handler.removeMessages(EMPTY);
        handler.sendEmptyMessage(EMPTY);
    }


    public static void handleHide() {
        isToastAlive = false;
        if (mView != null) {
            if (mView.getParent() != null) {
                mWM.removeView(mView);
            }
            mView = null;
        }
    }
}